import { createSlice } from "@reduxjs/toolkit";
import http from '@/utils/http'

// 定义用户store
const userStore = createSlice({
    name: 'user',
    initialState: {
        token: localStorage.getItem('token') || '',
    },
    reducers: {
        // 同步修改token方法
        setToken(state, action) {
            state.token = action.payload
            localStorage.setItem('token', action.payload)
        },
        // 同步删除token方法
        removeToken(state) {
            state.token = ''
            localStorage.removeItem('token')
        }
    }
})

const { setToken, removeToken } = userStore.actions

// 异步修改token方法
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await http.post('/authorizations', loginForm)
        dispatch(setToken(res.data.token))
        // 返回数据给组件使用
        return res
    }
}

// 导出异步方法
export { fetchLogin, removeToken }
// 导出store
export default userStore.reducer